import os
import json
import dify_helper
import pandas as pd
import argparse
import configparser
from tqdm import tqdm

def run_mapping(dh:dify_helper.DifyHelper,content_txt_path:str,title_json_path:str,out_story_json_path:str):
    with open(content_txt_path,'r') as f:
        content = f.read()
    section_arr = content.splitlines()
    with open(title_json_path,'r') as f:
        title = json.load(f)
    title_arr = title['title_arr']
    sencond_title_arr = []
    mapping_arr = []
    for title_obj in title_arr:
        f_node = {'title':title_obj['name'],'children':[]}
        for child in title_obj['child']:
            f_node['children'].append({'title':child,'content':''})
        mapping_arr.append(f_node)
        children = title_obj['child']
        sencond_title_arr = sencond_title_arr+children
    sencond_title_str = '\n'.join(sencond_title_arr)
    
    content_title_arr = []
    for section in tqdm(section_arr):
        if section.strip() == '':
            continue
        res = dh.send_workflow({
            'section_content':section,
            'second_title':sencond_title_str
        })
        title = res['text'].strip()
        content_title_arr.append({'title':title,'content':section})
    # print(content_title_arr)
    for mapping_obj in mapping_arr:
        for child in mapping_obj['children']:
            for content_title_obj in content_title_arr:
                if child['title'].strip() == content_title_obj['title'].strip():
                    child['content'] = f"{child['content']}\n{content_title_obj['content']}"
    
    with open(out_story_json_path,'w') as f: 
        json.dump(mapping_arr,f)

        

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="dify批量运行器")
    parser.add_argument('-rctp',"--raw_content_txt_path", type = str, help = "原始采访文件地址txt",default="/Users/zyy/Library/CloudStorage/OneDrive-个人/同心医联/24需求/10/回忆录-结构重整测试/回忆录全文.txt")
    parser.add_argument('-rtjp',"--raw_title_json_path", type = str, help = "原始故事大纲文件地址json",default="/Users/zyy/Library/CloudStorage/OneDrive-个人/同心医联/24需求/10/回忆录-结构重整测试/提纲.json")
    parser.add_argument('-osjp',"--out_story_json_path", type = str, help = "输出重整结构故事文件地址json",default="/Users/zyy/Library/CloudStorage/OneDrive-个人/同心医联/24需求/10/回忆录-结构重整测试/重整结构.json")
    args = parser.parse_args()
    config = configparser.ConfigParser()
    config.read("config.ini")
    base_url = "http://39.96.64.172:18863/v1"
    dh = dify_helper.DifyHelper(base_url,'app-ISfhFQp7wd1m6XgQ1NRgOJPU')
    run_mapping(dh,args.raw_content_txt_path,args.raw_title_json_path,args.out_story_json_path)
    